<template>
  <div class="page-container">
    <header-nav v-if="!isMiniProgram"/>
    <div class="form-container">
      <activity-info :info="activityInfo"/>
      <media :query="{minWidth: 768}">
        <div class="pc-media">
          <div class="form-title">
            <div>填写报名信息</div>
          </div>
          <!-- 扫码登录 -->
          <van-popup v-model="wxLoginQrcodeShow">
            <div id="WxQrcode">
              <iframe
                :src="`https://open.weixin.qq.com/connect/qrconnect?appid=wx0e89055f8943b237&scope=snsapi_login&redirect_uri=${currentUrl}&state=&login_type=jssdk&self_redirect=false`"
                frameborder="0"
                scrolling="no"
                width="300px"
                height="400px"
              ></iframe>
            </div>
          </van-popup>
        </div>
      </media>
      <media :query="{maxWidth: 768}">
        <div class="mb-media">
          <div class="form-title">
            <div>填写报名信息</div>
          </div>
        </div>
      </media>
      <van-cell-group>
        <div v-for="(i,n) in ConfigList" :key="n">
          <keep-alive>
            <text-input v-if="i.type=='text'" :config="i"/>
            <!-- 文本输入 -->
            <code-input v-if="i.type=='code'" :config="i"/>
            <!-- 验证码 -->
            <text-picker v-if="i.type=='picker'" :config="i"/>
            <!-- 单项文本选择 -->
            <area-picker v-if="i.type=='area'" :config="i"/>
            <!-- 选择省市区 -->
            <upload-img v-if="i.type=='upload'" :config="i"/>
            <!-- 上传图片 -->
            <phone-input v-if="i.type=='phone'" :config="i"/>
            <radio-field v-if="i.type=='radio'" :config="i"/>
            <card-input v-if="i.type=='IDCard'" :config="i"/>
            <textarea-field v-if="i.type=='textarea'" :config="i"/>
            <mobile-field v-if="i.type=='mobile'" :config="i"/>
            <certi-field v-if="i.type=='certificate'" :config="i"/>
            <dietary-field v-if="i.type=='dietary'" :config="i"/>
            <addr-field v-if="i.type=='addr'" :config="i"/>
            <quest-field v-if="i.type=='questionnaire'" :config="i"/>
          </keep-alive>
        </div>
      </van-cell-group>
      <div class="submit-btn" v-if="ConfigList.length>0">
        <media :query="{minWidth: 768}">
          <div class="total-info">
            <!-- <div class="total-num">
              总计：
              <span>{{ticketNum}}</span>张
            </div>
            <div class="total-money">
              总额：
              <span>{{totalPrice|formatPrice}}</span>
            </div> -->
          </div>
        </media>
        <van-button size="large" @click="FormSubmit" :disabled="!canSubmit">立即报名</van-button>
      </div>
    </div>
    <media :query="{minWidth: 768}">
      <footer-nav/>
    </media>
  </div>
</template>

<script>
import $ from 'jquery';
import Media from 'vue-media';
import Header from '../components/header';
import Footer from '../components/footer';
import ActivityInfo from '../components/ActivityInfo';
import TextInput from '../components/TextInput';
import CodeInput from '../components/CodeInput';
import TextPicker from '../components/TextPicker';
import AreaPicker from '../components/AreaPicker';
import UploadImg from '../components/UploadImg';
import PhoneInput from '../components/PhoneInput';
import IDCardInput from '../components/IDCardInput';
import RadioField from '../components/RadioField';
import TextareaField from '../components/TextareaField';
import MobileField from '../fields/MobileField';
import AddrField from '../fields/AddrField';
import CertificateField from '../fields/CertificateField';
import DietaryField from '../fields/DietaryField';
import QuestionnaireField from '../fields/QuestionnaireField';
export default {
  name: 'SignPage',
  data() {
    return {
      focusIndex: null,
      canSubmit: false,
      ConfigList: [],
      questInfo: [],
      activityInfo: {},
      ticketInfo: JSON.parse(localStorage['TicketInfo']),
      ticketNum: this.$store.state.BuyNum,
      isMiniProgram: false,
      wxLoginQrcodeShow: false,
      currentUrl: encodeURIComponent(window.location.href),
      shareUrl: ''
    };
  },
  computed: {
    totalPrice() {
      let price = 0;
      this.ticketInfo.forEach(item => {
        price += item.Fee;
      });
      return this.ticketNum * price;
    }
  },
  filters: {
    formatPrice: function(value) {
      return '￥' + value.toFixed(2);
    }
  },
  created() {
    let ua = window.navigator.userAgent.toLowerCase();
    if (this.$route.query.SessionID) {
      // 小程序内
      this.$store.commit('SET_SESSIONID', this.$route.query.SessionID);
      this.isMiniProgram = true;
    } else if (/MicroMessenger/i.test(ua)) {
      // weixin内
      if (this.$cookies.isKey('token')) {
        this.getLoginInfo(this.$cookies.get('token'));
      } else {
        this.$dialog
          .alert({
            message: '检测到您还未登录，点击确定使用微信登录',
            confirmButtonText: '微信一键登录'
          })
          .then(() => {
            window.location.href = `http://es.11cm.com.cn/WeiXinManage/GetWeiXinOpenID?ST=${
              this.$route.params.st
            }&ReferrerUrl=${encodeURIComponent(window.location.href)}`;
          });
      }
    }
    this.$store.commit('SET_USERAGENT', window.navigator.userAgent);
    this.$store.commit('SET_ST', this.$route.params.st);
    localStorage.setItem('st', this.$route.params.st);
    if (this.$route.query.OpenID) {
      localStorage.setItem('OpenId', this.$route.query.OpenID);
      this.$store.commit('SET_OPENID', this.$route.query.OpenID);
    }
    if (this.$route.query.PromotionCode) { // 推广码
      this.$store.commit('SET_PROMOTIONCODE', this.$route.query.PromotionCode);
      this.shareUrl = `${window.location.href.split('#')[0]}#/sign/${this.$route.params.st}?PromotionCode=${this.$route.query.PromotionCode}`;
    } else {
      this.shareUrl = `${window.location.href.split('#')[0]}#/sign/${this.$route.params.st}`;
    }
    if (this.$route.query.userType) {
      this.$store.commit('SET_USERTYPE', this.$route.query.userType);
    }
    var that = this;
    $.ajax({
      type: 'GET',
      url:
        that.baseUrl +
        '/api/Activity/get?st=' +
        that.$store.state.UserInfo.ST +
        '&userType=' +
        that.$store.state.UserInfo.UserTypeEnum,
      success: function(res) {
        that.buildFormJson(res);
        that.ConfigList.forEach(i => {
          // 将参数传入表单中
          if (i.key === 'name' && that.$route.query.Name) {
            i.value = that.$route.query.Name;
          }
          if (i.key === 'phone' && that.$route.query.Phone) {
            i.value = that.$route.query.Phone;
          }
          if (i.type === 'mobile' && that.$route.query.Phone) {
            i.data.forEach(j => {
              if (j.key === 'phone') {
                j.value = that.$route.query.Phone;
              }
            });
          }
        });
        that.activityInfo = res;
      }
    });
    $.ajax({
      type: 'POST',
      url: that.baseUrl + '/api/Activity/GetWeixinShare',
      data: {
        ST: that.$store.state.UserInfo.ST,
        UserType: that.$store.state.UserInfo.UserTypeEnum,
        URL: window.location.href.split('#')[0]
      },
      success: function(res) {
        document.title = res.Theme;
        that.wxShare(res, that.shareUrl);
      }
    });
  },
  components: {
    media: Media,
    'header-nav': Header,
    'footer-nav': Footer,
    'activity-info': ActivityInfo,
    'text-input': TextInput,
    'code-input': CodeInput,
    'text-picker': TextPicker,
    'area-picker': AreaPicker,
    'upload-img': UploadImg,
    'phone-input': PhoneInput,
    'card-input': IDCardInput,
    'radio-field': RadioField,
    'textarea-field': TextareaField,
    'mobile-field': MobileField,
    'addr-field': AddrField,
    'certi-field': CertificateField,
    'dietary-field': DietaryField,
    'quest-field': QuestionnaireField
  },
  methods: {
    getLoginInfo(token) {
      var that = this;
      $.ajax({
        type: 'GET',
        url: that.baseUrl + '/api/account/get',
        headers: { Authorization: token },
        success: function(res) {
          if (res.State) {
            localStorage.setItem('Unionid', res.Unionid);
            that.$store.commit('SET_UNIONID', res.Unionid);
            localStorage.setItem('OpenId', res.OpenID);
            that.$store.commit('SET_OPENID', res.OpenID);
          } else {
            that.$toast(res.Message);
          }
        }
      });
    },
    FormSubmit() {
      // 表单提交
      if (this.$cookies.isKey('token') || this.isMiniProgram) {
        var that = this;
        this.questInfo = JSON.parse(
          JSON.stringify(that.$store.state.UserInfo.QuestionnaireItems)
        );
        if (this.questInfo) {
          this.questInfo.forEach(i => {
            if (i.ControlType < 3 && i.ControlValue != null) {
              if (i.ControlType == 0) {
                i.ChooseValue = i.ChooseValue.join(',');
              }
              i.ControlValue = i.ControlValue.join(',');
            }
          });
          this.$store.commit('SET_QUEST', this.questInfo);
        }
        var submitInfo = JSON.parse(JSON.stringify(that.$store.state.UserInfo));
        for (var x in submitInfo) {
          // 清空值为空的项
          if (submitInfo[x] === '' || submitInfo[x] === null) {
            delete submitInfo[x];
          }
        }
        $.ajax({
          type: 'POST',
          url: `${that.baseUrl}/api/user/addUserInfo`,
          contentType: 'application/json;charset=utf-8',
          data: JSON.stringify(submitInfo),
          success: function(res) {
            if (res.State) {
              window.location.href =
                that.baseUrl +
                '/Q/' +
                that.$store.state.UserInfo.ST +
                '/true?phone=' +
                that.$store.state.UserInfo.Phone;
            } else {
              that.$toast(res.Message);
            }
          }
        });
      } else {
        let u = window.navigator.userAgent;
        if (/iPhone|iPod|Android|Mobile|ios|SymbianOS/i.test(u)) {
          // 移动端
          if (/MicroMessenger/i.test(u)) {
            // 微信内
            this.$dialog
              .alert({
                message: '检测到您还未登录，点击确定使用微信一键登录'
              })
              .then(() => {
                window.location.href = `http://es.11cm.com.cn/WeiXinManage/GetWeiXinOpenID?ST=${
                  this.$route.params.st
                }&ReferrerUrl=${encodeURIComponent(window.location.href)}`;
              });
          } else {
            let skipUrl = `${window.location.href}&Name=${
              this.$store.state.UserInfo.Name
            }&Phone=${this.$store.state.UserInfo.Phone}`;
            window.location.href = `#/login?ReferrerUrl=${encodeURIComponent(
              skipUrl
            )}`;
          }
        } else {
          // pc端
          this.wxLoginQrcodeShow = true;
        }
      }
    }
  },
  watch: {
    $route: {
      handler: function(val, oldVal) {
        if (val.query.code) {
          this.wxLoginQrcodeShow = false;
        }
      },
      deep: true
    },
    ConfigList: {
      handler: function(val, oldVal) {
        var abc = true;
        val.forEach(i => {
          if (i.must) {
            if (this.trims(i.value) == '') {
              return (abc = false);
            }
          }
          if (i.type == 'questionnaire') {
            // 调查表选项
            i.data.forEach(item => {
              if (item.IsRequire) {
                if (item.ControlType > 2) {
                  if (item.ChooseValue == null || item.ChooseValue == '') {
                    return (abc = false);
                  }
                } else if (item.ControlType == 0) {
                  if (item.ChooseValue.length == 0 || item.ChooseValue == null) {
                    return (abc = false);
                  }
                } else {
                  if (
                    item.ChooseValue == null ||
                    item.ChooseValue == '' ||
                    item.ChooseValue == '请选择' + item.ControlName
                  ) {
                    return (abc = false);
                  }
                }
              }
            });
          }
          if (i.data && i.data.length > 0) {
            i.data.forEach(j => {
              if (j.must) {
                if (this.trims(j.value) == '') {
                  return (abc = false);
                }
              }
            });
          }
        });
        if (abc) {
          this.canSubmit = true;
        } else {
          this.canSubmit = false;
        }
      },
      deep: true
    }
  }
};
</script>

